<template>
  <div class="chat-container">
    <!-- 顶部信息栏 -->
    <div class="chat-header">
      <h2>医生聊天室</h2>
      <div class="user-info">
        <span>当前用户：{{ username }}</span>
        <el-button type="danger" @click="disconnect" size="small">退出</el-button>
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content">
      <!-- 左侧医生列表 - 始终显示 -->
      <div class="doctor-list-container">
        <h3>医生列表</h3>
        <div class="doctor-item-wrapper">
          <div v-for="doctor in docters" :key="doctor.docterId" class="doctor-item">
            <el-avatar :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${doctor.docterId}`" size="small"></el-avatar>
            <span>{{ doctor.docterName }}</span>
            <!-- 显示未读消息数 -->
            <el-badge v-if="unreadCounts[doctor.docterId] > 0" :value="unreadCounts[doctor.docterId]" class="item"/>
            <!-- 添加私聊按钮 -->
            <el-button type="text" size="small" @click.stop="selectDoctor(doctor)" class="chat-btn">私聊</el-button>
          </div>
          <!-- 当没有医生时显示提示 -->
          <div class="empty-tip" v-if="docters.length === 0">暂无医生数据</div>
        </div>
      </div>

      <!-- 右侧聊天窗口 - 仅在选择医生后显示 -->
      <div class="chat-window" v-if="selectedDoctor">
        <!-- 聊天窗口头部 -->
        <div class="chat-window-header">
          <el-avatar :src="`https://api.dicebear.com/7.x/avataaars/svg?seed=${selectedDoctor.docterId}`" size="small"></el-avatar>
          <span>{{ selectedDoctor.docterName }}</span>
          <el-button type="text" size="small" @click="clearChat()">清空聊天</el-button>
        </div>
        
        <!-- 聊天消息区域 -->
        <div class="message-list">
          <!-- 在消息显示区域 -->
          <div v-for="message in filteredMessages" :key="getUniqueMessageKey(message)" class="message-item">
            <div v-if="message.type === 'SYSTEM'" class="system-message">
              {{ message.content }}
            </div>
            <div v-else-if="message.from === userId" class="self-message">
              <div class="message-header">
                <span class="sender">我</span>
                <span class="time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-content">
                {{ message.content }}
              </div>
            </div>
            <div v-else class="other-message">
              <div class="message-header">
                <span class="sender">{{ getDoctorNameById(message.from) }}</span>
                <span class="time">{{ formatTime(message.timestamp) }}</span>
              </div>
              <div class="message-content">
                {{ message.content }}
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天输入区域 -->
        <div class="chat-footer">
          <el-input v-model="inputMessage" placeholder="请输入消息内容" @keyup.enter.native="sendMessage" style="flex: 1; margin-right: 10px;"></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </div>
      </div>
      
      <!-- 未选择医生时的提示 -->
      <div class="no-selection" v-else>
        <p>请从左侧选择一位医生开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script>
import WebSocketService from '../../service/websocket.service.js';
import axios from 'axios';

export default {
  name: 'ChatView',
  data() {
    return {
      username: '',
      userId: '',
      docters: [], // 医生列表
      messages: [], // 所有消息列表
      onlineUsers: [], // 在线用户列表
      inputMessage: '', // 输入框内容
      wsService: null, // WebSocket服务实例
      selectedDoctor: null, // 当前选择的医生
      unreadCounts: {}, // 各医生未读消息数
      privateChatTarget: null, // 私聊目标
      selectedUserId: null // 选中的用户ID
    };
  },
  mounted() {
    // 从localStorage获取用户名
    this.username = 10
    // 优先使用后端颁发的 userId，其次回落到 username，避免与后端使用的数值ID不匹配
    this.userId = 10
    if (!this.userId) {
      this.$router.push('/login');
      return;
    }

    // 初始化WebSocket连接
    this.initWebSocket();
    // 加载医生列表
    this.loadDocterList();
  },
  beforeDestroy() {
    // 组件销毁前断开WebSocket连接
    if (this.wsService) {
      this.wsService.disconnect();
    }
  },
  computed: {
    // 根据当前选中的聊天对象过滤消息
    filteredMessages() {
      if (!this.privateChatTarget || !this.selectedUserId) {
        return [];
      }
      
      // 将所有比较值转换为字符串，确保类型一致
      const currentUserId = String(this.userId);
      const targetUserId = String(this.selectedUserId);
      
      // 筛选出与当前选中用户相关的消息
      return this.messages.filter(msg => {
        // 系统消息始终显示
        if (msg.type === 'SYSTEM') {
          return true;
        }
        
        // 将消息中的from和to也转换为字符串进行比较
        const msgFrom = String(msg.from);
        const msgTo = String(msg.to);
        
        // 只显示与当前用户的私聊消息，且必须是医生角色或自己发送的消息
        return ((msgFrom === currentUserId && msgTo === targetUserId) || 
                (msgFrom === targetUserId && msgTo === currentUserId)) && 
               (msg.role === 'DOCTOR' || msgFrom === currentUserId);
      });
    }
  },
  methods: {
    // 加载医生列表
    loadDocterList() {
      axios.get('/api/docter/findDocters').then(response => {
        this.docters = response.data.data;
        // 初始化每个医生的未读数为0
        this.docters.forEach(doctor => {
          this.$set(this.unreadCounts, doctor.docterId, 0);
        });
      }).catch(error => {
        console.error('加载医生列表失败:', error);
      });
    },

    // 初始化WebSocket连接
    initWebSocket() {
      // 创建WebSocket服务实例（使用 userId 建立会话，保证后端按ID路由）
      this.wsService = new WebSocketService(this.userId);

      // 设置消息回调函数 - 接收并处理WebSocket消息
      this.wsService.setOnMessageCallback((message) => {
        this.handleMessage(message);
      });

      // 设置状态回调函数 - 处理WebSocket连接状态变化
      this.wsService.setOnStatusCallback((status) => {
        this.handleStatusChange(status);
      });

      // 连接WebSocket服务器
      this.wsService.connect();
    },

    // 处理接收到的消息 - 只接收医生角色的消息或自己发送的消息
    handleMessage(message) {
      try {
        // 解析消息，如果是字符串则解析为JSON对象
        const msg = typeof message === 'string' ? JSON.parse(message) : message;
        
        // 只接收医生角色的消息或自己发送的消息，确保用户只与医生通信
        if (msg.type === 'SYSTEM' || msg.role === 'DOCTOR' || msg.from === this.userId) {
          // 只添加非系统消息到消息列表
          this.messages.push(msg);
          // 滚动到底部显示最新消息
          this.$nextTick(() => {
            const messageList = this.$el.querySelector('.message-list');
            if (messageList) {
              messageList.scrollTop = messageList.scrollHeight;
            }
          });
        }
      } catch (error) {
        console.error('解析消息失败:', error, '原始消息:', message);
      }
    },

    // 选择医生开始聊天
    selectDoctor(doctor) {
      this.selectedDoctor = doctor;
      // 设置私聊目标和选中的用户ID
      this.privateChatTarget = doctor.docterId;
      this.selectedUserId = doctor.docterId;
      // 重置未读数
      this.$set(this.unreadCounts, doctor.docterId, 0);
      
      // 滚动到消息列表底部
      this.$nextTick(() => {
        const messageList = this.$el.querySelector('.message-list');
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight;
        }
      });
    },
    
    // 发送消息
    sendMessage() {
      // 检查是否已选择聊天对象
      if (!this.selectedDoctor) {
        this.$message.warning('请先选择一位医生');
        return;
      }

      // 检查消息内容是否为空
      if (!this.inputMessage.trim()) {
        this.$message.warning('请输入消息内容');
        return;
      }

      // 构建消息对象
      const message = {
        type: 'USER',
        from: this.userId,
        to: this.selectedDoctor.docterId,
        content: this.inputMessage,
        timestamp: new Date().getTime(),
        role: 'USER' // 用户端设置角色为USER
      };

      // 通过WebSocket发送消息
      this.wsService.sendMessage(message);
      
      console.log(JSON.stringify(message))
      // 将发送的消息添加到本地消息列表中，实现消息的即时显示
      this.messages.push(message);
      
      // 滚动到底部显示最新消息
      this.$nextTick(() => {
        const messageList = this.$el.querySelector('.message-list');
        if (messageList) {
          messageList.scrollTop = messageList.scrollHeight;
        }
      });

      // 清空输入框
      this.inputMessage = '';
    },

    // 根据userId获取医生名称（用于显示）
    getDoctorNameById(userId) {
      const doctor = this.docters.find(doc => String(doc.docterId) === String(userId));
      return doctor ? doctor.docterName : '未知医生';
    },
    
    // 处理WebSocket连接状态变化
    handleStatusChange(status) {
      console.log('WebSocket状态变化:', status);
      if (status === 'CLOSED') {
        this.$message.error('WebSocket连接已关闭');
        this.$router.push('/login');
      } else if (status === 'ERROR') {
        this.$message.error('WebSocket连接出错');
      }
    },
    
    // 断开连接
    disconnect() {
      // 断开WebSocket连接
      if (this.wsService) {
        this.wsService.disconnect();
      }

      // 清除localStorage中的用户名
      localStorage.removeItem('username');
      localStorage.removeItem('userId');
      
      // 跳转到登录页面
      this.$router.push('/login');
    },

    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp);
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${hours}:${minutes}:${seconds}`;
    },

    // 生成唯一消息ID
    getUniqueMessageKey(message) {
      if (message.type === 'SYSTEM') {
        return `${message.type}_${message.timestamp}`;
      } else {
        const recipient = message.to || 'ALL';
        return `${message.from}_${recipient}_${message.type}_${message.timestamp}`;
      }
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.chat-header {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.chat-content {
  flex: 1;
  display: flex;
  overflow: hidden;
  padding: 20px;
  gap: 20px;
}

/* 医生列表样式 */
.doctor-list-container {
  width: 280px;
  background-color: #fff;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.doctor-list-container h3 {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #e6e6e6;
  background-color: #fafafa;
  font-size: 16px;
  border-radius: 5px 5px 0 0;
}

.doctor-item-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.doctor-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  margin-bottom: 8px;
  background-color: #f5f7fa;
  border-radius: 8px;
  gap: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.doctor-item:hover {
  background-color: #e6f7ff;
  transform: translateX(5px);
}

.doctor-item span {
  flex: 1;
  font-size: 14px;
}

.chat-btn {
  padding: 4px 12px;
  font-size: 12px;
  color: #1890ff;
  border: 1px solid #d9d9d9;
  height: auto;
}

.chat-btn:hover {
  color: #40a9ff;
  border-color: #40a9ff;
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 20px;
  font-size: 14px;
}

/* 聊天窗口样式 */
.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-window-header {
  padding: 15px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e6e6e6;
  background-color: #fafafa;
}

.chat-window-header span {
  font-weight: 500;
  font-size: 16px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #fafafa;
}

.message-item {
  margin-bottom: 20px;
}

.system-message {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin: 10px 0;
}

.self-message, .other-message {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.self-message {
  align-items: flex-end;
  margin-left: auto;
}

.other-message {
  align-items: flex-start;
  margin-right: auto;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
  font-size: 12px;
  color: #666;
}

.message-content {
  padding: 10px 15px;
  border-radius: 10px;
  background-color: #fff;
  border: 1px solid #e6e6e6;
  word-break: break-word;
  line-height: 1.5;
}

.self-message .message-content {
  background-color: #95ec69;
  border: none;
}

/* 未选择医生时的提示 */
.no-selection {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #999;
  font-size: 16px;
}

/* 底部输入区域 */
.chat-footer {
  padding: 20px;
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-footer .el-input__inner {
  min-height: 40px;
  font-size: 14px;
  padding: 8px 15px;
}

.chat-footer .el-button {
  height: 40px;
  padding: 0 20px;
}
</style>